<template>
  <!-- 新增从业人员 / 编辑从业人员 -->
  <view>
    <view class="staffNewEditor" v-if="!visibleCamera">
      <view class="content">
        <view class="content-item">
          <view class="title">身份信息</view>
          <view><u-line></u-line></view>
          <u-cell-group :border="false">
            <!-- 身份证号 -->
            <view class="idcard-style">
              <u-cell :titleStyle="titleStyle" title="国籍" isLink :rightIconStyle="rightIconStyle"
                @click.native="hadleShowPicker('nationality', 'nationality')">
                <text slot="icon" class="required">*</text>
                <view slot="value" :class="form.nationality_text ? 'cell-noEmpty' : 'cell-empty'">
                  {{ form.nationality_text || "请选择" }}
                </view>
              </u-cell>
              <u-cell :titleStyle="titleStyle" title="证件类型" isLink :rightIconStyle="rightIconStyle"
                @click.native="hadleShowPicker('certificate_type', 'idType')">
                <text slot="icon" class="required">*</text>
                <view slot="value" :class="form.idType ? 'cell-noEmpty' : 'cell-empty'">
                  {{ form.idType_text || "请选择" }}
                </view>
              </u-cell>
              <u-cell :titleStyle="titleStyle" title="证件号码">
                <text slot="icon" class="required">*</text>
                <u-input v-model="form.idCard" :type="form.idType == 10 ? 'idcard' : 'text'" data-type="workPerson"
                  placeholder="请输入" slot="value" fontSize="14" placeholderClass="placeholderClass" inputAlign="right"
                  border="none" :maxlength="18" :required="true" @blur="idCardHandle">
                </u-input>
                <view class="scan-wrapper" @click="handleCamera" slot="right-icon" v-show="form.idType == 10">
                  <image src="/static/icons/scan.png" class="scan-img"></image>
                </view>
              </u-cell>
            </view>
            <!-- 姓名 -->
            <u-cell :titleStyle="titleStyle" title="姓名">
              <text slot="icon" class="required">*</text>
              <u-input v-model="form.personName" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                :required="true"></u-input>
            </u-cell>
            <u-cell :titleStyle="titleStyle" title="出生日期" isLink :rightIconStyle="rightIconStyle"
              @click="cellTimeClick('birthday')">
              <text slot="icon" class="required">*</text>
              <view slot="value" :class="form.birthday ? 'cell-noEmpty' : 'cell-empty'">
                {{ form.birthday || "请选择" }}
              </view>
            </u-cell>
            <u-cell :titleStyle="titleStyle" title="性别" isLink :rightIconStyle="rightIconStyle"
              @click.native="hadleShowPicker('sex_type', 'sex')">
              <text slot="icon" class="required">*</text>
              <view slot="value" :class="form.sex ? 'cell-noEmpty' : 'cell-empty'">
                {{ form.sex_text || "请选择" }}
              </view>
            </u-cell>
            <u-cell v-if="form.idType == 10" :titleStyle="titleStyle" title="民族" isLink :rightIconStyle="rightIconStyle"
              @click.native="hadleShowPicker('nation', 'nation')">
              <text slot="icon" class="required">*</text>
              <view slot="value" :class="form.nation ? 'cell-noEmpty' : 'cell-empty'">
                {{ form.nation_text || "请选择" }}
              </view>
            </u-cell>
            <!-- <u-cell :titleStyle="titleStyle" title="户籍地址">
              <text slot="icon" class="required">*</text>
              <u-input v-model="form.residenceAddress" data-type="workPerson" placeholder="请输入" slot="value"
                fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                :required="true"></u-input>
            </u-cell>
            <u-cell :titleStyle="titleStyle" title="户籍地所属区县">
              <text slot="icon" class="required">*</text>
              <u-input v-model="form.residenceCode_text" data-type="workPerson" placeholder="请选择" slot="value"
                fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                :required="true" @click.native="handleCityPicker('residenceCode')" disabled
                disabled-color="#fff"></u-input>
            </u-cell>
            <view class="hint" style="font-size: 20rpx; color: #f56c6c;" v-if="areaList.length">
              户籍所属区县由系统自动匹配，如匹配不准确或未匹配到请务必手动修改!
            </view> -->

            <!-- 所属岗位 -->
            <!-- <u-cell :titleStyle="titleStyle" title="所属岗位">
              <text slot="icon" class="required">*</text>
              <u-input
                v-model="form.station"
                data-type="workPerson"
                placeholder="请输入"
                slot="value"
                fontSize="14"
                placeholderClass="placeholderClass"
                inputAlign="right"
                border="none"
                :maxlength="30"
                :required="true"
              ></u-input>
            </u-cell> -->

            <!-- 户籍地址 -->
            <!--  <u-cell :titleStyle="titleStyle" title="户籍地址">
              <text slot="icon" class="required">*</text>
              <u-input v-model="form.residenceAddress" data-type="workPerson" placeholder="请输入" slot="value"
                fontSize="14" placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                :required="true"></u-input>
            </u-cell> -->

            <!-- 现居地址 -->
            <!-- <u-cell :titleStyle="titleStyle" title="现居地址">
              <text slot="icon" class="required">*</text>
              <u-input v-model="form.currentAddress" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30"
                :required="true"></u-input>
            </u-cell> -->

            <!-- 联系方式 -->
            <u-cell :titleStyle="titleStyle" title="手机号">
              <text slot="icon" class="required">*</text>
              <u-input v-model="form.mobile" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
                placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="30" :required="true"
                @blur="phoneHandle"></u-input>
            </u-cell>

            <!-- 职务名称 -->
            <!--     <u-cell :titleStyle="titleStyle" title="职务名称" clickable isLink :rightIconStyle="rightIconStyle"
              @click="cellClick('text', 'position')">
              <text slot="icon" class="required">*</text>
              <view slot="value" :class="form.positionDesc ? 'cell-noEmpty' : 'cell-empty'">
                {{ form.positionDesc || "请选择" }}
              </view>
            </u-cell> -->

            <u-cell :titleStyle="titleStyle" title="入职时间" clickable isLink :rightIconStyle="rightIconStyle"
              @click="cellTimeClick('entryTime')">
              <text slot="icon" class="required">*</text>
              <view slot="value" :class="form.entryTime ? 'cell-noEmpty' : 'cell-empty'">
                {{ form.entryTime || "请选择" }}
              </view>
            </u-cell>

            <u-cell :titleStyle="titleStyle" title="人脸照片" :border="false">
            </u-cell>
            <view class="upload-view">
              <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic(1)" name="file" :maxCount="1"
                width="110" height="90">
                <image :src="baseImgUrl + 'upload-icon2.png'" style="width: 220rpx; height: 180rpx"></image>
              </u-upload>
            </view>

            <!--  <view class="title">健康证信息</view>
            <u-cell :titleStyle="titleStyle" title="证件照片" :border="false">
            </u-cell>
            <view class="upload-view">
              <u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic(2)" name="file" :maxCount="1"
                width="310" height="180">
                <image :src="baseImgUrl + 'card_4.png'" style="width: 640rpx; height: 360rpx"></image>
              </u-upload>
            </view>

            <u-cell :titleStyle="titleStyle" title="发证日期" clickable isLink :rightIconStyle="rightIconStyle"
              @click="cellTimeClick('healthTime')">
              <view slot="value" :class="form.healthTime ? 'cell-noEmpty' : 'cell-empty'">
                {{ form.healthTime || "请选择" }}
              </view>
            </u-cell> -->
            <!-- 过期时间 -->
            <!-- <u-cell
              :titleStyle="titleStyle"
              title="过期时间"
              clickable
              isLink
              :rightIconStyle="rightIconStyle"
              data-type="healthValidityPeriod"
              @click="cellTimeClick('healthValidityPeriod')"
            >
              <text slot="icon" class="required">*</text>
              <view
                slot="value"
                :class="form.healthValidityPeriod ? 'cell-noEmpty' : 'cell-empty'"
              >
                {{ form.healthValidityPeriod || "请选择" }}
              </view>
            </u-cell> -->
          </u-cell-group>
        </view>
      </view>

      <view class="btns">
        <button class="reset-btn lt cancelBtn" type="primary" @click="resethandle">
          取消
        </button>
        <button class="submit-btn" type="primary" @click="submitHandle">
          保存
        </button>
      </view>

      <!-- <yy-city-picker :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false"></yy-city-picker> -->
      <yy-city-picker-all v-if="cityPickerVisible" :visible="cityPickerVisible" @confirm="onCityConfirm"
        @cancel="cityPickerVisible = false" :default-value="defaultCityCode"></yy-city-picker-all>

      <u-picker closeOnClickOverlay v-if="pickerShow" :show="pickerShow" :columns="pickerData" keyName="text"
        @confirm="onPickerConfirm" @cancel="pickerShow = false" @close="pickerShow = false"
        :defaultIndex="defaultIndex"></u-picker>

      <!-- 时间选择器 -->
      <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="date"
        :formatter="formatter" :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose"
        @cancel="pickerTimeClose(1)" @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
    </view>
    <yy-photo-mask :visible.sync="visibleCamera" :baseImgUrl="baseImgUrl" :clientId="clientId"
      :clientSecret="clientSecret" @generateFilePath="onGenerateFilePath" @parsedSuccess="onParsedSuccess">
    </yy-photo-mask>
  </view>
</template>

<script>
  import {
    employeesOperation,
    employeesDetail
  } from "@/api/home.js";
  import {
    findEnableDictItemsbyCode,
  } from "@/api/api.js";
  import {
    Toast,
    navBack,
    checkIDCard,
    formatters,
    dayTurnTime,
    getBase64Two,
    uniTrim,
    useNetWork,
    isLoading,
    getHeader,
    uploadFile,
    selectNation,
    setDefaultProvinceCode,
    parseIDCard,
  } from "@/utils/util.js";
  import mixin from "@/utils/mixin.js";
  import cityPickerMixin from "../../utils/city-picker-mixin";
  import pickerMixin from "../../utils/picker-mixin";
  import _ from '@/utils/lodash.js'
  import moment from "../../utils/moment";

  export default {
    name: "staffNewEditor",
    mixins: [mixin, cityPickerMixin, pickerMixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        imgPrefix: uni.getStorageSync('imgPrefix'),
        clientSecret: this.$clientSecret,
        options: {},
        form: {
          nation: '',
          nation_text: '',
          // residenceAddress: '',
          // residenceCode: '',
          // residenceCode_text: ''
          nationality: 'CHN',
          nationality_text: '中国',
          idType: '10',
          idType_text: '身份证',
          birthday: ''
        },
        errorType: ["none"],
        fileList: [],
        fileList2: [],
        fileList3: [],
        visibleCamera: false,

        areaList: [],
        defaultCityCode: '',
      };
    },
    watch: {},
    onLoad(options) {
      this.options = options;
      if (options.id) {
        employeesDetail({
          id: options.id
        }).then((res) => {
          if (res.code == 200) {
            this.options = res.result;
            this.form = res.result;
            // this.form.positionDesc = options.position;
            this.form.nation_text = res.result.nationName
            // this.form.residenceCode_text = res.result.residenceCodeName
            if (this.form.personImage) {
              this.fileList.push({
                url: this.imgPrefix + this.form.personImage
              });
            }
            if (this.form.healthImage) {
              this.fileList2.push({
                url: this.form.healthImage
              });
            }
            if (this.form.idCardUrl) {
              this.fileList3.push({
                url: this.form.idCardUrl
              });
            }
          }
        });
      }

      uni.setNavigationBarTitle({
        title: options.num == 1 ? "新增从业人员" : "编辑从业人员",
      });

      if (this.options.rank == 7) {
        this.form.position = this.options.rank;
        // this.form.positionDesc = "保安";
      }
    },
    methods: {
      handleIdCardChange() {
        let params = {
          idCard: this.form.idCard,
        }
        if (this.form.idType == 10) {
          setDefaultProvinceCode.call(this, params, ({
            code,
            address
          }) => {
            this.defaultCityCode = code
          })
        }
      },
      phoneHandle() {
        if (this.form.mobile && !this.$u.test.mobile(this.form.mobile)) {
          Toast("请输入正确的手机号");
          return;
        }
      },
      idCardHandle() {
        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag && this.form.idType == 10) {
          Toast("请输入正确的证件号码");
          return;
        }
        this.setBirthdayAdnSex(this.form.idCard)
        this.handleIdCardChange()
      },
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick(e) {
        // this.cellType = e.currentTarget.dataset.type;
        this.cellType = e;
        var minDateNum = +new Date(); //获取当前时间的毫秒数

        switch (this.cellType) {
          case "healthTime":
            this.minDate = new Date(1971, 0, 1).getTime();
            this.maxDate = minDateNum;

            this.timeValue = this.maxDate;
            break;
          case "healthValidityPeriod":
            this.minDate = dayTurnTime(this.form.healthTime);
            this.maxDate = new Date(2099, 0, 1).getTime();

            this.timeValue = this.minDate;
            break;
          case "entryTime":
            this.minDate = new Date(1971, 0, 1).getTime();
            this.maxDate = minDateNum;

            this.timeValue = this.maxDate;
            break;

          case "birthday":
            this.minDate = new Date(1800, 0, 1).getTime();
            this.maxDate = minDateNum;
            this.timeValue = this.maxDate;
            break;

          default:
            break;
        }

        // if (this.cellType == "healthValidityPeriod" && !this.form.healthTime) {
        //   Toast("请选择发证日期");
        //   return false;
        // }

        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },
      pickerTimeClose(e) {
        if (e) {
          switch (this.cellType) {
            case "healthTime":
              this.form.healthTime = "";
              this.form.healthValidityPeriod = "";
              break;
            case "healthValidityPeriod":
              this.form.healthValidityPeriod = "";
              break;
            case 'birthday':
              this.form.birthday = ''
              break
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          switch (this.cellType) {
            case "healthTime":
              this.form.healthTime = formatters(arr, "YY/MM/DD");
              break;
            case "healthValidityPeriod":
              this.form.healthValidityPeriod = formatters(arr, "YY/MM/DD");
              break;
            case "entryTime":
              this.form.entryTime = formatters(arr, "YY/MM/DD");
              break;

            case "birthday":
              this.form.birthday = moment(arr).format("YYYY/MM/DD")
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },

      afterRead(info) {
        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: info.file.url,
            name: "file",
            formData: {
              type: 6,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList.push({
              url: fullPath
            });
            _this.form.personImage = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      afterRead2(info) {
        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: info.file.url,
            name: "file",
            formData: {
              type: 7,
            },
          })
          .then((res) => {
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList2.push({
              url: fullPath
            });
            _this.form.healthImage = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      deletePic(num) {
        if (num == 1) {
          this.fileList = [];
          this.form.personImage = "";
        } else if (num == 2) {
          this.fileList2 = [];
          this.form.healthImage = "";
        } else if (num == 3) {
          this.fileList3 = [];
          this.form.idCardUrl = "";
        }
      },
      afterReadThree(info) {
        let _this = this;

        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: _this.clientId,
            client_secret: _this.clientSecret,
          },
          success(res) {
            _this.base64Handle(res.data.access_token, info);
          },
        });
      },
      base64Handle(token, info) {
        let _this = this;

        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            uni.request({
              url: `https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${token}`,
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: {
                id_card_side: "front",
                image: res,
              },
              success(resbai) {
                let {
                  statusCode,
                  data
                } = resbai;
                if (statusCode == 200 && data.words_result["姓名"]) {
                  _this.$set(
                    _this.form,
                    "personName",
                    data.words_result.姓名.words
                  );
                  _this.$set(
                    _this.form,
                    "idCard",
                    data.words_result.公民身份号码.words
                  );
                  // _this.$set(
                  //   _this.form,
                  //   "residenceAddress",
                  //   data.words_result.住址.words
                  // );
                  _this.uploadCard(info.file.url);
                  return;
                }

                Toast("未识别");
                _this.uploadCard(info.file.url);
                // Toast("请上传正确的身份证证件照片");
              },
            });
          });
      },
      handleCamera() {
        this.visibleCamera = true;
      },
      onParsedSuccess({
        userName,
        idcard,
        domicileAddress,
        words_result,
        nation
      }) {
        this.$set(
          this.form,
          "personName",
          userName
        );
        this.$set(
          this.form,
          "idCard",
          idcard
        );
        // this.$set(
        //   this.form,
        //   "residenceAddress",
        //   domicileAddress
        // );
        this.handleIdCardChange()
        let nationOption = selectNation(this.dictMapping, nation)
        if (nationOption) {
          this.form.nation = nationOption.value
          this.form.nation_text = nationOption.text
        }
        this.setBirthdayAdnSex(idcard)
      },
      onGenerateFilePath(file) {
        this.uploadCard(file)
      },
      uploadCard(fileurl) {
        useNetWork(); // 判断是否有网络
        isLoading();

        let _this = this;
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type: 20,
            },
          })
          .then((res) => {
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList3.push({
              url: fullPath
            });
            _this.form.idCardUrl = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      resethandle() {
        uni.navigateBack();
      },
      submitHandle() {
        let {
          idCardUrl,
          idCard,
          // residenceAddress,
          currentAddress,
          personImage,
          personName,
          // positionDesc,
          entryTime,
          mobile,
          healthTime,
          healthImage,
        } = this.form;


        if (!idCard || !uniTrim(idCard)) {
          Toast("请输入身份证号");
          return;
        }

        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag && this.form.idType == 10) {
          Toast("请输入正确的证件号码");
          return;
        }

        if (!personName || !uniTrim(personName)) {
          Toast("请输入姓名");
          return;
        }
        if (!this.form.nation && this.form.idType == 10) {
          Toast('请选择民族！')
          return
        }
        // if (!this.form.residenceAddress || !uniTrim(this.form.residenceAddress)) {
        //   Toast('请填写户籍地址！')
        //   return
        // }
        // if (!this.form.residenceCode) {
        //   Toast('请选择户籍所属区县！')
        //   return
        // }

        // if (!residenceAddress || !uniTrim(residenceAddress)) {
        //   Toast("请输入户籍地址");
        //   return;
        // }

        // if (!currentAddress || !uniTrim(currentAddress)) {
        //   Toast("请输入现居地址");
        //   return;
        // }

        if (!mobile || !uniTrim(mobile)) {
          Toast("请输入手机号");
          return;
        }

        if (mobile && !this.$u.test.mobile(mobile)) {
          Toast("请输入正确的手机号");
          return;
        }

        // if (!positionDesc || !uniTrim(positionDesc)) {
        //   Toast("请选择职务名称");
        //   return;
        // }

        if (!entryTime) {
          Toast("请选择入职时间");
          return;
        }

        // if (!personImage || !uniTrim(personImage)) {
        //   Toast("请上传人脸头像");
        //   return;
        // }

        let data = {
          companyMessageId: this.options.companyMessageId,
          ...this.form,
        };

        employeesOperation(data).then((res) => {
          if (res.code == 200) {
            Toast(data.id ? "编辑成功" : "添加成功");
            navBack("back", data.id ? 2 : 1);
            return;
          }

          Toast(res.message);
        });
      },
      setBirthdayAdnSex(idCard) {
        const {
          birthDate,
          gender
        } = parseIDCard(idCard)
        this.form.birthday = moment(birthDate).format("YYYY/MM/DD")
        this.form.sex = gender == '男' ? '1' : '2'
        this.form.sex_text = gender
      }
    },
  };
</script>

<style lang="scss" scoped>
  .staffNewEditor {
    flex: 1;
    background-color: #f9f9f9;

    .content {
      margin: 0 auto;
      margin-top: 20rpx;
      margin-bottom: 20rpx;
      border-radius: 8rpx;
      width: calc(100% - 35rpx);
      height: calc(100vh - 84px);
      overflow-y: auto;

      .content-item {
        padding: 25rpx;
        background: #fff;

        .title {
          padding: 20rpx 0;
          font-size: 36rpx;
          font-weight: bold;
        }

        .upload-view {
          padding-left: 30rpx;
        }
      }
    }

    .idcard-style {
      /deep/ .u-cell__body {
        padding-right: 0;
      }

      /deep/ .u-input__content__field-wrapper__field {
        padding-right: 8rpx !important;
      }
    }

    .u-input__content {
      width: 450rpx;
    }

    .scan-wrapper {
      padding: 10rpx;

      .scan-img {
        width: 30rpx;
        height: 27.73rpx;
      }
    }
  }
</style>